﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Windows.Forms;
using hamburgerwang.businfo;
using hamburgerwang.common;

namespace SuzhouBus
{
    public partial class FormStopQuery2 : Form
    {
        private string m_LastRealTimeHtml;
        private string m_SessionID;
        private bool m_AjaxPosted;

        public FormStopQuery2()
        {
            InitializeComponent();
        }

        private void buttonStopQuery_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.textBoxStop.Text.Trim().Length == 0)
                {
                    MessageBox.Show("请输入至少一个字.");
                    this.textBoxStop.Focus();
                    return;
                }
                this.buttonStopQuery.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();
                string url = Program.RealTimeProviderURL;
                HttpHelper httpHelper = new HttpHelper();
                httpHelper.OnGetCredential += new GetCredentialHandler(helper_OnGetCredential);
                this.m_LastRealTimeHtml = httpHelper.Get(url);
                m_AjaxPosted = false;
                m_SessionID = AspNetHelper.GetSessionID(httpHelper.Cookies);
                Application.DoEvents();
                Dictionary<string, string> postData = this.PrepareRealTimeData(true, "", "", this.textBoxStop.Text.Trim());
                this.m_LastRealTimeHtml = httpHelper.Post(url, postData);
                m_AjaxPosted = true;
                Application.DoEvents();
                string tableString = AspNetHelper.GetHtmlFieldInnerHtml(this.m_LastRealTimeHtml, "ctl00_ContentPlaceHolder_ctl00_ctl00_MessageCode", "span");
                BusStop[] stops = this.GetBusStops(tableString);
                this.comboBoxStops.DataSource = stops;
                Dictionary<string, string> busPostData = this.PrepareBusInfoData(this.textBoxStop.Text.Trim());
                HttpHelper busHelper = new HttpHelper();
                busHelper.Encoding = System.Text.Encoding.Default;
                Uri uri = new Uri(new Uri(Program.BusInfoProviderURL), "result_test.asp");
                string busHtml = busHelper.Post(uri.AbsoluteUri, busPostData);
                Application.DoEvents();
                string tablesHtml = AspNetHelper.GetHtmlFieldInnerHtml(busHtml, "form")[0];
                string[] tableList = AspNetHelper.GetHtmlFieldInnerHtml(tablesHtml, "table");
                BusLine[] lines = new BusLine[tableList.Length];
                for (int i = 0; i < tableList.Length; i++)
                {
                    BusLine line = new BusLine();
                    string[] trList = AspNetHelper.GetHtmlFieldInnerHtml(tableList[i], "tr");

                    string[] tdNoList = AspNetHelper.GetHtmlFieldInnerHtml(trList[1], "td");
                    line.No = AspNetHelper.GetHtmlFieldInnerHtml(tdNoList[1], "span")[1];
                    string[] tdRoutineList = AspNetHelper.GetHtmlFieldInnerHtml(trList[5], "td");
                    line.Routine = tdRoutineList[1].Substring(tdRoutineList[1].IndexOf("：") + 1).Split(new char[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                    string[] tdDescList = AspNetHelper.GetHtmlFieldInnerHtml(trList[7], "td");
                    line.Description = tdDescList[1];
                    line.Price = 0;
                    lines[i] = line;
                }
                this.comboBoxLines.DataSource = lines;
            }
            catch (ApplicationException ex)
            {

            }
            finally
            {
                this.buttonStopQuery.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private BusStop[] GetBusStops(string tableString)
        {
            BusStop[] stops;
            string[] trList = AspNetHelper.GetHtmlFieldInnerHtml(tableString, "tr");
            if (trList.Length > 0)
            {
                stops = new BusStop[trList.Length - 1];
                for (int i = 1; i < trList.Length; i++)
                {
                    BusStop stop = new BusStop();
                    string[] tdList = AspNetHelper.GetHtmlFieldInnerHtml(trList[i], "td");
                    stop.ID = tdList[1];
                    stop.Name = string.Format("{0} ({1}{2})", tdList[0], tdList[3], tdList[5]);
                    stop.Description = tdList[4];
                    stops[i - 1] = stop;
                }
            }
            else
            {
                stops = new BusStop[0];
            }
            return stops;
        }

        private Dictionary<string, string> PrepareBusInfoData(string stopName)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();

            data.Add("kind", @"线路站点");
            data.Add("zhandian", stopName);
            data.Add("submit", @"提交");
            return data;
        }

        private Dictionary<string, string> PrepareRealTimeData(bool searchCode, string busLine, string stopCode, string stopName)
        {
            string eventValidation;
            string viewState;
            if (m_AjaxPosted)
            {
                eventValidation = AspNetHelper.GetUpdatePanelFieldValue(m_LastRealTimeHtml, "__EVENTVALIDATION");
                viewState = AspNetHelper.GetUpdatePanelFieldValue(m_LastRealTimeHtml, "__VIEWSTATE");
            }
            else
            {
                eventValidation = AspNetHelper.GetHtmlFieldValue(this.m_LastRealTimeHtml, "__EVENTVALIDATION", "input");
                viewState = AspNetHelper.GetHtmlFieldValue(this.m_LastRealTimeHtml, "__VIEWSTATE", "input");
            }
            Dictionary<string, string> data = new Dictionary<string, string>();
            if (searchCode)
            {
                data.Add("ctl00%24ContentPlaceHolder%24ctl00%24ScriptManager1", "ctl00$ContentPlaceHolder$ctl00$ctl00$UpdatePanel2|ctl00$ContentPlaceHolder$ctl00$ctl00$SearchCode");
                data.Add("ctl00%24ContentPlaceHolder%24ctl00%24ctl00%24SearchCode", @"查询");
            }
            else
            {
                data.Add("ctl00%24ContentPlaceHolder%24ctl00%24ScriptManager1", "ctl00$ContentPlaceHolder$ctl00$ctl00$UpdatePanel2|ctl00$ContentPlaceHolder$ctl00$ctl00$Search");
                data.Add("ctl00%24ContentPlaceHolder%24ctl00%24ctl00%24Search", @"查询");
            }
            data.Add("ctl00_ContentPlaceHolder_ctl00_ScriptManager1_HiddenField", "");
            data.Add("ctl00_ContentPlaceHolder_treeview_ExpandState", "nennnenennnnnnnennnnnnnennnnennn");
            data.Add("ctl00_ContentPlaceHolder_treeview_SelectedNode", "");
            data.Add("__EVENTARGUMENT", "");
            data.Add("__EVENTTARGET", "");
            data.Add("ctl00_ContentPlaceHolder_treeview_PopulateLog", "");
            data.Add("__VIEWSTATE", Uri.EscapeDataString(viewState));
            data.Add("__EVENTVALIDATION", Uri.EscapeDataString(eventValidation));
            data.Add("ctl00%24ContentPlaceHolder%24ctl00%24ctl00%24BusLine", busLine);
            data.Add("ctl00%24ContentPlaceHolder%24ctl00%24ctl00%24StandCode", stopCode);
            data.Add("ctl00%24ContentPlaceHolder%24ctl00%24ctl00%24StandName", stopName);
            data.Add("__ASYNCPOST", "true");
            return data;
        }

        private NetworkCredential helper_OnGetCredential()
        {
            using (FormProxy formProxy = new FormProxy())
            {
                if (DialogResult.OK == formProxy.ShowDialog(this))
                {
                    Application.DoEvents();
                    return formProxy.Credential;
                }
                else
                {
                    throw new ApplicationException();
                }
            }
        }

        private void buttonDistance_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.comboBoxLines.Text.Trim().Length == 0)
                {
                    MessageBox.Show("请输入公交线路.");
                    this.comboBoxLines.Focus();
                    return;
                }
                if (this.comboBoxStops.Items.Count <= 0)
                {
                    MessageBox.Show("请先查询站台.");
                    this.textBoxStop.Focus();
                    return;
                }
                else if (this.comboBoxStops.SelectedIndex < 0)
                {
                    MessageBox.Show("请选择站台.");
                    this.comboBoxStops.Focus();
                    return;
                }

                this.buttonDistance.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();
                string url = Program.RealTimeProviderURL;
                HttpHelper httpHelper = new HttpHelper();
                httpHelper.OnGetCredential += new GetCredentialHandler(helper_OnGetCredential);
                Dictionary<string, string> postData = this.PrepareRealTimeData(false, this.comboBoxLines.Text.Trim(), this.comboBoxStops.SelectedValue.ToString(), this.textBoxStop.Text.Trim());
                Application.DoEvents();
                this.m_LastRealTimeHtml = httpHelper.Post(url, postData);
                Application.DoEvents();
                this.labelDistance.Text = AspNetHelper.GetHtmlFieldInnerHtml(m_LastRealTimeHtml, "ctl00_ContentPlaceHolder_ctl00_ctl00_Message", "span");
            }
            catch (ApplicationException ex)
            {

            }
            finally
            {
                this.buttonDistance.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void comboBoxLines_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxLines.SelectedIndex >= 0)
            {
                BusLine line = (BusLine)this.comboBoxLines.SelectedItem;
                this.listBoxRoutine.DataSource = line.Routine;
                this.labelDistance.Text = line.Description;
            }
        }

        private void comboBoxStops_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxStops.SelectedIndex >= 0)
            {
                BusStop stop = (BusStop)this.comboBoxStops.SelectedItem;
                this.labelDistance.Text = stop.Description;
            }
        }

        private void listBoxRoutine_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listBoxRoutine_DoubleClick(object sender, EventArgs e)
        {
            int index = this.listBoxRoutine.IndexFromPoint(this.listBoxRoutine.PointToClient(Cursor.Position));
            if (index >= 0)
            {
                string stopName = this.listBoxRoutine.Items[index].ToString();
                int indexChinese = stopName.IndexOf('（');
                if (indexChinese >= 0)
                {
                    stopName = stopName.Substring(0, indexChinese);
                }
                int indexEnglish = stopName.IndexOf('(');
                if (indexEnglish >= 0)
                {
                    stopName = stopName.Substring(0, indexEnglish);
                }
                this.textBoxStop.Text = stopName;
            }
        }
    }
}
